package wenjun.du.androidart.ipc.messenger

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_messenger.*
import wenjun.du.androidart.R

/**
 * 将服务组件注册到另外一个进程中，绑定服务之后 进行跨进程通讯
 * 使用messenger信使通过传递message对象 进行跨进程单线通信
 *
 * */
class MessengerActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MessengerActivity"
    }

    private lateinit var mMessengerBinder: IBinder

    private lateinit var mHandler: Handler

    private lateinit var mContext: ServiceConnection
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messenger)
        val intent = Intent(this, MessengerService::class.java)
        mContext = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                if (service != null) {
                    mMessengerBinder = service
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {

            }

        }
        mHandler = object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    2 ->
                        Toast.makeText(
                            this@MessengerActivity,
                            "${msg.data.getString("service_data")}",
                            Toast.LENGTH_SHORT
                        ).show()
                }
            }
        }
        bindService(intent, mContext, Context.BIND_AUTO_CREATE)
        main_messenger.setOnClickListener {
            //创建messenger对象 发送单条消息给服务端
            val messenger = Messenger(mMessengerBinder)
            val message = Message.obtain()
            message.what = 1
            message.replyTo = Messenger(mHandler)
            val bundle = Bundle()
            bundle.putString("data", "hello 我是来自客户端的问候！")
            message.data = bundle
            messenger.send(message)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(mContext)
    }
}